package com.umeox.watch.audiobooks.utils;


import androidx.annotation.NonNull;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程管理类
 *
 * @author zl
 * @date 2018/7/24
 */

public class ThreadPoolExecutorUtils extends ThreadPoolExecutor {

    /**
     * 核心线程池大小（默认大小为5）
     */
    private static final int CORE_POOL_SIZE = 5;
    /**
     * 最大线程池队列大小
     */
    private static final int MAXIMUM_POOL_SIZE = 128;
    /**
     * 保持存活时间，当线程数大于corePoolSize的空闲线程能保持的最大时间。
     */
    private static final int KEEP_ALIVE = 1;
    /**
     * 阻塞队列。当核心线程都被占用，且阻塞队列已满的情况下，才会开启额外线程。
     */
    private static BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(10);


    private static final ThreadFactory factory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        @Override
        public Thread newThread(@NonNull Runnable runnable) {
            return new Thread(runnable, "线程" + mCount.getAndDecrement());
        }
    };

    /**
     * 默认工作线程数5
     */
    public ThreadPoolExecutorUtils() {
        this(CORE_POOL_SIZE);
    }

    /**
     * @param poolSize 工作线程数
     */
    public ThreadPoolExecutorUtils(int poolSize) {
        this(poolSize, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, workQueue, factory);
    }

    public ThreadPoolExecutorUtils(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
    }

    /**
     * 判断当前线程池是否繁忙
     *
     * @return
     */
    public boolean isBusy() {
        return getActiveCount() >= getCorePoolSize();
    }

    /**
     * 提交任务
     *
     * @param runnable
     */
    @Override
    public void execute(Runnable runnable) {
        super.execute(runnable);
    }
}
